<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="find.name" placeholder="角色名模糊查询" class="handle-input mr10"></el-input>
                
                <el-button type="success" @click="Show()">查询</el-button>
                <el-button type="danger" @click="Delete()">批删</el-button>
                <el-button type="success" @click="OpenUser()">添加</el-button>
                <el-button type="primary" @click="OpenAuthority()">为角色添加权限</el-button>
            </div>
            <el-row>
                <el-col :span="24">
                    <!--角色列表-->
                    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"> </el-table-column>
                        <el-table-column label="ID" width="120">
                            <template slot-scope="scope">{{ scope.row.rId }}</template>
                        </el-table-column>
                        <el-table-column prop="rName" label="角色名" width="120"> </el-table-column>
                        <el-table-column prop="rText" label="角色描述" width="300"> </el-table-column>
                        <el-table-column label="状态" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <div v-if="scope.row.status == 0">
                                    <el-tag type="danger">禁用</el-tag>
                                </div>
                                <div v-else>
                                    <el-tag type="success">启用</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createdTime" label="创建时间" show-overflow-tooltip> </el-table-column>
                        <el-table-column label="操作" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit"  @click="OpenUpdateRole(scope.row)">编辑 </el-button>
                                <el-button type="danger" icon="el-icon-delete"  @click="singleDelete(scope.row.rId)">删除 </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!--分页-->
                    <div class="pagination">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="find.PageIndex"
                            :page-sizes="[10, 20, 30, 40]"
                            :page-size="find.PageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="SCount"
                        >
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
        </div>

        <!--角色添加对话框-->
        <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
            <el-form
                ref="elForm"
                :model="carInfomation"
                :rules="carInfomationrules"
                size="medium"
                label-width="141px"
                label-position="left"
            >
                <el-form-item label="角色名称" prop="rName">
                    <el-input
                        v-model="carInfomation.rName"
                        placeholder="请输入角色名称"
                        clearable
                        :style="{ width: '100%' }"
                        @blur="UniqueRName(carInfomation.rName)"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="rText">
                    <el-input
                        v-model="carInfomation.rText"
                        placeholder="请输入角色描述"
                        clearable
                        :style="{ width: '100%' }"
                    ></el-input>
                </el-form-item>
                <el-form-item label="角色状态" prop="status">
                    <el-select v-model="carInfomation.status" placeholder="请选择角色状态" clearable :style="{ width: '100%' }">
                        <el-option
                            v-for="(item, index) in statusOptions"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = flase">取消</el-button>
                <el-button type="primary" @click="submitForm" :disabled=a>确定</el-button>
            </div>
        </el-dialog>
        <!--角色修改对话框-->
        <el-dialog title="编辑角色" :visible.sync="UpdatedialogFormVisible">
            <el-form ref="elForm" :model="rowRole" :rules="carInfomationrules" size="medium" label-width="141px" label-position="left">
                <el-form-item label="角色名称" prop="rName">
                    <el-input v-model="rowRole.rName" placeholder="请输入角色名称" clearable :style="{ width: '100%' }" @blur="UniqueRName(rowRole.rName)"> </el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="rText">
                    <el-input v-model="rowRole.rText" placeholder="请输入角色描述" clearable :style="{ width: '100%' }"></el-input>
                </el-form-item>
                <el-form-item label="角色状态" prop="status">
                    <el-select v-model="rowRole.status" placeholder="请选择角色状态" clearable :style="{ width: '100%' }">
                        <el-option
                            v-for="(item, index) in statusOptions"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button  @click="UpdatedialogFormVisible = flase">取消</el-button>
                <el-button type="primary" @click="submitUpdateForm">确定</el-button>
            </div>
        </el-dialog>
        <!--角色权限添加对话框-->
        <el-dialog title="添加角色权限" :visible.sync="AuthoritydialogFormVisible" width="30%">
            <el-tree
                :data="tableDataAuthority"
                show-checkbox
                default-expand-all
                node-key="pId"
                ref="tree"
                highlight-current
                :props="defaultProps"
            >
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button  @click="AuthoritydialogFormVisible = flase">取消</el-button>
                <el-button type="primary" @click="addRolePermission()">确定</el-button>
            </div>
        </el-dialog>
        <!--菜单分配对话框-->
        <el-dialog title="菜单分配" :visible.sync="menusDialogFormVisible">
            <el-tree
                ref="tree"
                :data="menusTable"
                show-checkbox
                node-key="menusId"
                :props="{ value: 'menusId', label: 'menusName', children: 'children' }"
                :default-expanded-keys="[2, 3]"
                :default-checked-keys="[5]"
            >
            </el-tree>
            <br /><br /><br />
            <el-button type="primary" round @click="AddMenus()">分配菜单</el-button>
            &nbsp;&nbsp;&nbsp;
            <el-link type="danger" @click="menusDialogFormVisible = flase">取消</el-link>
        </el-dialog>
    </div>
</template>

<script>
import { getRoleList, uniqueRName, deleteRole, addRole, updateRole, getTreeAuthority, addTreeAuthority, getPer } from '@/api/role';

export default {
    name: 'role',
    data() {
        return {
            carInfomation: {
                rName: undefined,
                rText: undefined,
                status: undefined
            },
            a:false,
            carInfomationrules: {
                rName: [
                    {
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    }
                ],
                rText: [
                    {
                        required: true,
                        message: '请输入角色描述',
                        trigger: 'blur'
                    }
                ],
                status: [
                    {
                        required: true,
                        message: '请选择角色状态',
                        trigger: 'change'
                    }
                ]
            },
            statusOptions: [
                {
                    label: '启用',
                    value: 1
                },
                {
                    label: '停用',
                    value: 0
                }
            ],
            defaultProps: {
                children: 'children',
                label: 'pTitle',
            },
            //角色列表
            tableData: [],
            tableDataAuthority: [],
            //全选反选获取的数据
            multipleSelection: [],
            //添加角色
            //添加角色对话框
            dialogFormVisible: false,
            //对话框宽度
            formLabelWidth: '120px',
            //修改角色对话框
            UpdatedialogFormVisible: false,
            //权限列表
            authorityTable: [],
            //角色权限添加对话框
            AuthoritydialogFormVisible: false,
            //角色权限添加
            roleAuthority: {
                roleId: undefined,
                authorityId: undefined
            },
            //分页
            find: {
                name: undefined,
                PageIndex: 1,
                PageSize: 10
            },
            //总行数
            SCount: 0,
            //数组
            AuthorityNum: [],
            //菜单
            menusTable: [],
            //菜单对话框
            menusDialogFormVisible: false,
            id: {
                ids: undefined
            },
            rowRole: {
                rId: undefined,
                rName: undefined,
                rText: undefined,
                status: undefined,
                createdTime: undefined,
                createdUserID: undefined
            },
            rolePermission: {
                rId: undefined,
                pId: undefined
            }
        };
    },

    methods: {
        //全选反选
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //角色的显示
        Show() {
            getRoleList(this.find).then((res) => {
                this.tableData = res.data.pageList;
                this.SCount = res.data.totalCount;
            });
        },
        UniqueRName(rName) {
            uniqueRName( rName).then((res) => {
                console.log(res);
                if (res.data.msg === '该角色名是唯一') {
                    this.$message({
                        message: '该角色名是唯一',
                        type: 'success'
                    });
                    this.a=false;
                } else {
                    this.$message({
                        message: '请重新输入角色名字，该角色名重复',
                        type: 'warning'
                    });
                    this.a=true;
                }
            });
        },
        //页容量
        handleSizeChange(val) {
            this.find.PageSize = val;
            this.Show();
        },
        //上一页下一页
        handleCurrentChange(val) {
            this.find.PageIndex = val;
            this.Show();
        },
        //角色的批删
        Delete() {
            if (this.multipleSelection === undefined || this.multipleSelection.length === 0) {
                this.$message({
                    message: '请选择角色',
                    type: 'warning'
                });
                return;
            } else {
                if (confirm('是否确认删除？')) {
                    this.id.ids = this.multipleSelection.map((x) => x.rId).toString();
                    deleteRole(this.id).then((res) => {
                        if (res.code > 0) {
                            this.$message({
                                message: '角色删除成功',
                                type: 'success'
                            });
                            this.id.ids = undefined;
                            this.Show();
                        } else {
                            this.$message({
                                message: '角色删除失败',
                                type: 'warning'
                            });
                        }
                    });
                }
            }
        },
        //角色的单删
        singleDelete(Id) {
            if (confirm('是否确认删除？')) {
                this.id.ids = Id;
                deleteRole(this.id).then((res) => {
                    if (res.code > 0) {
                        this.$message({
                            message: '角色删除成功',
                            type: 'success'
                        });
                        this.id.ids = undefined;
                        this.Show();
                    } else {
                        this.$message({
                            message: '角色删除失败',
                            type: 'warning'
                        });
                    }
                });
            }
        },
        //打开用户的添加
        OpenUser() {
            this.dialogFormVisible = true;
        },
        //角色的添加
        submitForm() {
            this.$refs['elForm'].validate((valid) => {
                if (!valid) return;
                // TODO 提交表单
                addRole(this.carInfomation).then((res) => {
                    if (res.code > 0) {
                        this.$message({
                            message: '角色添加成功',
                            type: 'success'
                        });
                        this.carInfomation.rName = undefined;
                        this.carInfomation.rText = undefined;
                        this.carInfomation.status = undefined;
                        this.dialogFormVisible = false;

                        this.Show();
                    } else {
                        this.$message({
                            message: '角色添加失败',
                            type: 'warning'
                        });
                        this.dialogFormVisible = false;
                    }
                });
            });
        },
        resetForm() {
            this.$refs['elForm'].resetFields();
        },
        //打开角色的编辑
        OpenUpdateRole(row) {
            this.rowRole = row;
            this.UpdatedialogFormVisible = true;
        },
        //角色的编辑
        submitUpdateForm() {
            this.$refs['elForm'].validate((valid) => {
                if (!valid) return;
                // TODO 提交表单
                updateRole(this.rowRole).then((res) => {
                    if (res.code > 0) {
                        this.$message({
                            message: '角色修改成功',
                            type: 'success'
                        });
                    } else {
                        this.$message({
                            message: '角色修改失败',
                            type: 'warning'
                        });
                    }
                    this.UpdatedialogFormVisible = false;
                });
            });
        },
        //权限列表
        getAuthority() {
            //获取权限数据
            getTreeAuthority().then((res) => {
                // console.log('权限列表:', res);
                this.tableDataAuthority = res.data;
                this.FindRoleAuthority(); //把选中的角色ID所拥有的权限进行反填
            });
        },
        FindRoleAuthority() {
            getPer(this.multipleSelection.map((x) => x.rId)).then((res) => {
                this.$refs.tree.setCheckedKeys(res.data);
            });
        },
        //打开权限
        OpenAuthority() {
            if (this.multipleSelection === undefined || this.multipleSelection.length === 0 || this.multipleSelection.length > 1) {
                this.$message({
                    message: '请选择一个角色',
                    type: 'warning'
                });
                return;
            } else {
                this.rolePermission.rId = this.multipleSelection.map(x => x.rId);
                this.rolePermission.rId = parseInt(this.rolePermission.rId);
                this.AuthoritydialogFormVisible = true;
                this.getAuthority();
            }
        },
        //角色权限的添加
        addRolePermission() {
            this.rolePermission.pId = this.$refs.tree.getCheckedKeys().toString();
            addTreeAuthority(this.rolePermission).then((res) => {
                console.log('角色权限添加:', res);
                if (res.code > 0) {
                    this.$message({
                        message: '角色权限添加成功',
                        type: 'success'
                    });
                    this.rolePermission.rId = undefined;
                    this.rolePermission.pId = undefined;
                    this.AuthoritydialogFormVisible = false;
                } else {
                    this.$message({
                        message: '角色权限添加失败',
                        type: 'warning'
                    });
                    this.AuthoritydialogFormVisible = false;
                }
            });
        },
        //角色权限的反填
        FindRole() {
            this.roleAuthority.roleId = this.multipleSelection.map((x) => x.roleId).toString();
            FindRole({ RoleId: this.roleAuthority.roleId }).then((res) => {
                var num = res.data.map((x) => x.authorityId);
                this.AuthorityNum = num;
                this.$refs.tree.setCheckedKeys(this.AuthorityNum);
            });
        },
        //打开菜单
        OpenMenus() {
            if (this.multipleSelection === undefined || this.multipleSelection.length === 0 || this.multipleSelection.length > 1) {
                this.$message({
                    message: '请选择一个角色',
                    type: 'warning'
                });
                return;
            } else {
                this.menusDialogFormVisible = true;
                this.GetTreeMenus();
            }
        },
        //菜单列表
        GetTreeMenus() {
            GetTreeMenus().then((res) => {
                console.log('菜单列表:', res);
                this.menusTable = res.data;
            });
        },
        //为角色分配菜单
        AddMenus() {
            this.$message({
                message: '菜单分配成功',
                type: 'success'
            });
            this.menusDialogFormVisible = false;
        }
    },
    //挂载后
    mounted() {
        //角色权限
        this.Show();
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
